package com.future.service;

import com.future.cons.Const;
import com.future.lock.ZKLock;
import com.future.service.impl.CommonService;
import com.future.vo.Stock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2022/10/9 14:39
 */

@Service
@Qualifier(value = "zkServiceImpl")
public class ZkServiceImpl extends CommonService implements TradeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceImpl.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ZKLock zkLock;

    @Override
    public String lock() {
        InterProcessMutex lock = zkLock.getLock();
        try {
            lock.acquire();
            LOGGER.info("success get lock, start update DB");
            Object oldTicketSum = redisTemplate.opsForValue().get(Const.TICKET_SUM);
            int ticket;
            if (oldTicketSum == null || (ticket = Integer.parseInt(oldTicketSum + "")) < 1) {
                Stock stock = select(1);
                if (null != stock && stock.getStock() >= 1) {
                    ticket = stock.getStock();
                } else {
                    LOGGER.error("票数为空，停止抢票");
                    return "";
                }
            }
            LOGGER.info("current thread {} 剩余票数: {}", Thread.currentThread(), --ticket);
            redisTemplate.opsForValue().set(Const.TICKET_SUM, ticket);
            doDBUpdate(ticket);

            lock.release();

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return "BAD";
        } finally {
            try {
                lock.release();
                LOGGER.info("finish! start release lock");
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            }
        }
        return "OK";
    }

}
